package com.ssm.helong.shop.service.impl;

import com.ssm.helong.shop.Dao.GoodsAttributeMapper;
import com.ssm.helong.shop.service.GoodsAttributeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.Connection;

@Service
public class GoodsAttributeServiceImpl implements GoodsAttributeService {
    @Autowired
    private GoodsAttributeMapper goodsAttributeMapper;

    @Override
    public int updateStock(Integer id) {
        int upStock = goodsAttributeMapper.updateStock(id);
        return upStock;
    }

    @Override
    public int selectStock(Integer id) {
        int seStock = goodsAttributeMapper.selectStock(id);
        return seStock;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
    public int placeAnOrder(Integer id) {
        int stockNum = goodsAttributeMapper.selectStock(id);
        try {
            goodsAttributeMapper.updateStock(id);

            if (stockNum <= 0) {
                throw new Exception("库存不足");
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            System.out.println("库存不足，购买失败");
        }

        return stockNum;
    }
}
